<template>
  <div class="form">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="120px" label-position="right">
        <el-form-item label="Name">
          <el-input v-model="searchForm.name" placeholder="">
          </el-input>
        </el-form-item>
        <el-form-item label="VT SKU">
          <el-input v-model="searchForm.sku" placeholder="">
          </el-input>
        </el-form-item>
        <el-form-item label="Supplier SKU">
          <el-input v-model="searchForm.csku" placeholder="">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="Status" style="width: 260px;">
          <el-select v-model="searchForm.status" placeholder="" style="width: 140px;">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button type="primary" v-permission="['supperskus.store']" plain @click="productadd">+New</el-button>
          <el-button type="primary" v-permission="['supperskus.store']" plain @click="uploadData">Import</el-button>
          <el-button type="primary" v-permission="['supperskus.view']" plain @click="exportData">Export</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="title" label="Product" align="center" />
        <el-table-column label="VT UOM" width="120" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
          </template>
        </el-table-column>
        <el-table-column label="VT SKU" align="center">
          <template v-slot="scope">
            <span>{{scope.row.sku}}</span>
          </template>
        </el-table-column>
        <el-table-column label="Supplier SKU" align="center">
          <template v-slot="scope">
            <span @click="handleclear(scope.$index)"
              v-if="scope.row.csku !=null && scope.row.csku.length>0">{{scope.row.csku}} </span>
            <el-input v-else v-model="scope.row.inputvalue" placeholder="Enter Supplier's SKU" style="width: 65%;"
              @blur="handleUpdates(scope.row,scope.$index)" />
          </template>
        </el-table-column>


        <el-table-column label="Delivery time(days)" align="center">
          <template v-slot="scope">
            <span @click="handlecleardeliverytime(scope.$index)"
              v-if="scope.row.deliverytime != null && scope.row.deliverytime > 0">{{
              scope.row.deliverytime }} </span>
            <el-input v-else v-model="scope.row.inputvaluedeliverytime" placeholder="Enter Delivery time"
              style="width: 65%;" @blur="handleUpdatesdeliverytime(scope.row, scope.$index)" />
          </template>
        </el-table-column>


        <el-table-column label="Supplier UOM" align="center">
          <template v-slot="scope">
            <span @click="handleclearc(scope.$index)" v-if="scope.row.cskuom != null && scope.row.cskuom.length > 0">{{
              scope.row.cskuom }} </span>
            <el-input v-else v-model="scope.row.inputvaluec" placeholder="enter supplier UOM" style="width: 65%;"
              @blur="handleUpdatesc(scope.row, scope.$index)" />
          </template>
        </el-table-column>

        <el-table-column label="Common Price" align="center">
          <template v-slot="scope">
            <span>{{scope.row.proprice}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Created Time" width="220">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="200">
          <template slot-scope="scope">
            <el-button plain v-permission="['supperskus.destroy']" type="danger"
              @click="del(scope.row.skid)">Remove</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
    <UploadSku :show.sync="isShow" :module="module" :id="cid" />

    <div class="form">
      <el-dialog title="Add Product" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        customClass="customWidth" width="85%">
        <div class="toolbar">
          <el-form :inline="true" :model="searchForm1" class="demo-form-inline" label-width="100px"
            label-position="right">
            <el-form-item label="Name">
              <el-input v-model="searchForm1.name" @keyup.enter.native="search" placeholder="Enter Name">
              </el-input>
            </el-form-item>

            <el-form-item label="Category" prop="category_id" style="width: 360px;">
              <treeselect v-model="searchForm1.category_id" :options="deptOptions" :normalizer="normalizer"
                placeholder="Select Category" style="width: 250px;" @open="onOpen" @close="onClose" />
            </el-form-item>

            <el-form-item>
              <el-button @click="find1()" plain>Search</el-button>
              <el-button plain :disabled="multiplev" @click="handleadd">Add checked
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table" style="width: 90%">

          <el-table :data="filteredTableData" size="small" stripe border style="margin-top: 20px;"
            @selection-change="handleSelectionChange">

            <el-table-column type="selection" width="50" align="center" :selectable="isRowSelectable" />
            <el-table-column prop="name" label="Name" width="160" align="center" />
            <el-table-column label="Spec" width="100" align="center">
              <template v-slot="scope">
                <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
              </template>
            </el-table-column>
            <el-table-column label="Category" width="200" align="center">
              <template v-slot="scope">
                <span>{{ scope.row.category_name }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="sku" label="VT SKU" width="160" align="center" />

            <el-table-column label="Supplier SKU" align="center" width="160">
              <template v-slot="scope">
                <el-input v-model="scope.row.csku" style="width: 65%;" placeholder="Enter Supplier SKU"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="Delivery time(days)" align="center" width="160">
              <template v-slot="scope">
                <el-input v-model="scope.row.deliverytime" style="width: 65%;"
                  placeholder="Enter deliverytime"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="Supplier UOM" align="center" width="160">
              <template v-slot="scope">
                <el-input v-model="scope.row.cskuom" style="width: 65%;" placeholder="Enter Supplier UOM"></el-input>
              </template>
            </el-table-column>

            <el-table-column prop="price" label="Common Price" width="120" align="center" />

            <el-table-column label="Actions" width="100">
              <template slot-scope="scope">
                <el-button plain @click="addv(scope.row, scope.row.id)"
                  :disabled="isDisabled(scope.row.id)">add</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page">
          <el-pagination v-if="isPaginate1" background :current-page="page1.current_page" :page-sizes="page1.sizes"
            :page-size="page1.per_page" layout="prev, pager, next" :total="page1.total" @size-change="sizeChange1"
            @current-change="currentChange1" />
        </div>
      </el-dialog>
    </div>

  </div>
</template>
<script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {
    index as cateindex,
  } from "@/api/product_category";
  import CURD from "@/mixin/CURD";
  import {
    index as skulist,
    update as skupdate,
    exportData as skuexport
  } from "@/api/suppersku";
  import UploadSku from "@/components/UploadSku";
  export default {
    name: "skuIndex",
    components: {
      UploadSku,
      Treeselect
    },
    props: {
      id: {
        type: String,
        default: 0
      }
    },
    mixins: [CURD],
    data() {
      return {
        dialogFormVisible: false,
        status: [{
          id: null,
          name: "All",
        }, {
          id: "added",
          name: "Added",
        }, {
          id: "notadded",
          name: "Not Added",
        }],
        tableData: [],
        page: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        isPaginate1: true,
        page1: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        tableData1: [],
        searchForm1: {},
        cid: this.id,
        isEdit: false,
        isNew: false,
        formData: {},
        module: "suppersku",
        newTitle: "New suppersku",
        editTitle: "Edit suppersku",
        isPaginate: true,
        searchForm: {},
        imageUrl: "",
        dialogFormPasswordVisible: false,
        isUploadFile: false,
        importDialogVisible: false,
        fileReader: new FileReader(),
        isShow: false,
        categories: [],
        deptOptions: [],
        ids: [],
        oidlist: [],
        productdata: [],
        multiplev: false,
      };
    },
    computed: {
      filteredTableData() {
        // 过滤掉 ID 为 3 的数据
        return this.tableData1.filter(item => !this.isDisabled(item.id));
      }
    },
    async created() {
      this.searchForm.supper_id = this.cid;
      await this.fetchData();
      try {
        const {
          data
        } = await cateindex(1, 100); // 假设index是一个异步函数
        this.categories = data;
        // 调用handleTree方法处理数据
        this.deptOptions = this.handleTree(data, "id", "parent_id");
      } catch (error) {
        console.error('Failed to fetch categories:', error);
      }
    },
    methods: {
      isRowSelectable(row, selected) {
        // 返回 false 以禁用选择功能
        return !this.oidlist.includes(row.id);
      },
      isDisabled(id) {
        return this.oidlist.includes(id);
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async sizeChange1(val) {
        this.page1.per_page = val;
        await this.fetchData1();
      },
      async currentChange1(val) {
        this.page1.current_page = val;
        await this.fetchData1();
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.multiplev = !selection.length
      },
      goiscustomersku() {
        var isaar = false;
        for (var i = 0; i < this.ids.length; i++) {
          var pid = this.ids[i]
          for (var iv = 0; iv < this.tableData1.length; iv++) {
            if (this.tableData1[iv].id == pid) {
              if (this.tableData1[iv].csku) {
                console.log(this.tableData1[iv].csku, "ddddddddddddddddd")
              } else {
                console.log(this.tableData1[iv].csku, "eeeeeeeeeeeeeeeee")
                isaar = 1;
                return isaar;
              }
              if (this.tableData1[iv].cskuom) {
                console.log(this.tableData1[iv].cskuom, "ddddddddddddddddd")
              } else {
                console.log(this.tableData1[iv].cskuom, "eeeeeeeeeeeeeeeee")
                isaar = 2;
                return isaar;
              }
              if (this.tableData1[iv].deliverytime) {
                console.log(this.tableData1[iv].deliverytime, "ddddddddddddddddd")
              } else {
                console.log(this.tableData1[iv].deliverytime, "eeeeeeeeeeeeeeeee")
                isaar = 3;
                return isaar;
              }
            }
          }
        }
        return isaar;
      },
      async handleadd() {

        if (this.goiscustomersku() == 1) {
          this.$message.error("Please Enter Customer SKU")
          return
        }
        if (this.goiscustomersku() == 2) {
          this.$message.error("Please Enter Customer UOM")
          return
        }
        if (this.goiscustomersku() == 3) {
          this.$message.error("Please Enter Customer Deliverytime")
          return
        }
        for (var i = 0; i < this.ids.length; i++) {
          var pid = this.ids[i]
          for (var iv = 0; iv < this.tableData1.length; iv++) {
            if (this.tableData1[iv].id == pid) {
              if (this.oidlist.includes(pid)) {

              } else {
                this.oidlist.push(pid)
                this.tableData1[iv].supper_id = this.cid;
                this.tableData1[iv].title = this.tableData1[iv].name


                console.log(this.tableData1[iv], "this.tableData1[iv]")
                this.productdata.push(this.tableData1[iv])
              }
              break
            }
          }
        }
        console.log(this.productdata, "pddd")
        if (this.productdata.length > 0) {
          let {
            store
          } = require(`@/api/${this.module}`);
          let {
            info
          } = await store({
            procureditem: this.productdata
          });
          this.$message.success(info);
          this.dialogFormVisible = false
          this.fetchData()
          this.productdata = [];
        }
      },
      async addv(row, oid) {
        if (!row.deliverytime) {
          this.$message.error("Please Enter deliverytime")
          return
        }
        if (!row.cskuom) {
          this.$message.error("Please Enter UOM")
          return
        }
        if (row.csku) {
          if (this.oidlist.includes(oid)) {
            this.$message.error("The product has been added !")
          } else {
            this.oidlist.push(oid)
            console.log(row, "ddddddddddddddd")
            row.supper_id = this.cid;
            row.title = row.name
            row.deliverytime = row.deliverytime
            row.cskuom = row.cskuom
            this.productdata.push(row)
            let {
              store
            } = require(`@/api/${this.module}`);
            let {
              info
            } = await store({
              procureditem: this.productdata
            });
            this.$message.success(info);
            this.dialogFormVisible = false
            this.productdata = [];
            this.fetchData()
          }
        } else {
          this.$message.error("Please Enter Customer SKU")
        }
      },

      find1(event) {
        this.$nextTick().then(() => {
          this.page1.current_page = 1;
          this.fetchData1();
        });
      },
      productadd() {
        this.fetchData1()
        this.dialogFormVisible = true
      },
      async fetchData1() {
        let {
          index
        } = require(`@/api/product`);
        const res = await index(
          this.page1.current_page,
          this.page1.per_page,
          this.searchForm1
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData1 = data;
        } else {
          this.tableData1 = res.data;
        }

        for (var iv = 0; iv < this.tableData1.length; iv++) {
          this.tableData1[iv].csku = ""
          this.tableData1[iv].cskuom = this.tableData1[iv].uom
        }


        console.log(res.meta)
        if (res.meta) {
          this.isPaginate1 = true;
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page1 = Object.assign(this.page1, res.meta);
        } else {
          this.isPaginate1 = false; // 不分页
        }
      },
      handleclear(index) {
        this.tableData[index].inputvalue = this.tableData[index].csku
        this.tableData[index].bakcsku = this.tableData[index].csku
        this.tableData[index].csku = null
      },
      handleclearc(index) {
        this.tableData[index].inputvaluec = this.tableData[index].cskuom
        this.tableData[index].bakcskuom = this.tableData[index].cskuom
        this.tableData[index].cskuom = null
      },
      handleUpdatesc(row, index) {

        this.$confirm('This operation will update the data. Do you want to continue?', 'title', {
          confirmButtonText: 'confirm',
          cancelButtonText: 'cancel',
          type: 'warning'
        }).then(() => {
          const id = row.skid
          var fd = {
            cskuom: row.inputvaluec,
            id: row.skid,
            action: "cskuom"
          }
          skupdate(fd).then(res => {
            this.$message.success(res.info)
            this.tableData[index].cskuom = row.inputvaluec
          });
        }).catch(() => {
          this.tableData[index].cskuom = this.tableData[index].bakcskuom ? this.tableData[index].bakcskuom :
            null
          this.$message({
            type: 'info',
            message: 'Cancelled'
          });
        });
      },
      handlecleardeliverytime(index) {
        this.tableData[index].inputvaluedeliverytime = this.tableData[index].deliverytime
        this.tableData[index].bakdtyim = this.tableData[index].deliverytime
        this.tableData[index].deliverytime = null
      },
      handleUpdatesdeliverytime(row, index) {
        this.$confirm('This operation will update the data. Do you want to continue?', 'title', {
          confirmButtonText: 'confirm',
          cancelButtonText: 'cancel',
          type: 'warning'
        }).then(() => {
          const id = row.skid
          var fd = {
            deliverytime: row.inputvaluedeliverytime,
            id: row.skid,
            action: "deliverytime"
          }
          skupdate(fd).then(res => {
            console.log(res.info)
            this.$message({
              type: 'success',
              message: res.info
            });
            this.tableData[index].deliverytime = row.inputvaluedeliverytime
          });
        }).catch(() => {
          console.log(this.tableData[index].bakdtyim, "this.tableData[index].bakdtyim")
          this.tableData[index].deliverytime = this.tableData[index].bakdtyim ? this.tableData[index]
            .bakdtyim : 1
          this.$message({
            type: 'info',
            message: 'Cancelled'
          });
        });
      },

      async exportData() {
        const resv = await skuexport(this.page.current_page,
          this.page.per_page,
          this.searchForm);
        this.exportFile("data", resv);
      },
      exportFile(fileName, res) {
        const content = res;
        const blob = new Blob([content], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          window.URL.revokeObjectURL(elink.href); // 释放 URL对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          window.navigator.msSaveBlob(blob, fileName);
        }
      },
      uploadData() {
        this.isShow = true;
      },
      saveData() {
        this.save("ruleForm");
      },
      handleUpdates(row, index) {
        this.$confirm('This operation will be updated. Do you want to continue?', 'title', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          const id = row.skid
          var fd = {
            csku: row.inputvalue,
            id: row.skid,
            action: "csku"
          }
          skupdate(fd).then(res => {
            //this.$message.success(res.info)
            this.tableData[index].csku = row.inputvalue
            this.$message({
              type: 'success',
              message: 'Confirm success!'
            });
          });

        }).catch(() => {
          console.log(this.tableData[index].bakcsku, "this.tableData[index].bakcsk")
          this.tableData[index].csku = this.tableData[index].bakcsku ? this.tableData[index].bakcsku : null
          this.$message({
            type: 'info',
            message: 'Cancel'
          });
        });
      },
      async fetchData() {
        this.searchForm.supper_id = this.cid;
        const res = await skulist(
          this.page.current_page,
          this.page.per_page,
          this.searchForm
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data.map(item => {
            item.inputvalue = ""
            item.inputvaluec = ""
            item.inputvaluedeliverytime = ""
            return item
          })
          for (var iv = 0; iv < this.tableData.length; iv++) {
            console.log(this.tableData[iv].product_id)
            this.oidlist.push(this.tableData[iv].product_id)
          }
        } else {
          this.tableData = res.data.map(item => {
            item.inputvalue = ""
            item.inputvaluec = ""
            item.inputvaluedeliverytime = ""
            return item
          });
          for (var iv = 0; iv < this.tableData.length; iv++) {
            console.log(this.tableData[iv].product_id)
            this.oidlist.push(this.tableData[iv].product_id)
          }
        }
        let {
          rules
        } = require(`@/model/${this.module}`);
        this.rules = rules;
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      async add() {
        let {
          Model
        } = require(`@/model/${this.module}`);
        this.formData = new Model();
        this.isNew = true;
        this.isEdit = false;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      setTitle() {
        this.title = this.isNew === true ? this.newTitle : this.editTitle;
        this.cmdTitle = this.isNew === true ? "save" : "modify";
      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.supper_id = this.cid;
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success(info);
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await store(this.formData);
                this.$message.success(info);
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error(
              "Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      parseErrors(errors) {
        let info = "";
        let name = errors.name;
        if (Array.isArray(name)) {
          name.forEach((item) => {
            info += item + ",";
          });
        }
        info = info.substring(0, str.length - 1);
        return info;
      },
      async edit(id) {
        let {
          show
        } = require(`@/api/${this.module}`);
        let {
          data
        } = await show(id);
        this.formData = data;
        this.isNew = false;
        this.isEdit = true;
        this.setTitle();
        this.dialogFormVisible = true;
      },
      async del(id) {
        try {
          await this.$confirm("This operation will permanently delete data. Do you want to continue?",
            "prompt", {
              confirmButtonText: "determine",
              cancelButtonText: "cancel",
              type: "warning"
            });
          let {
            destroy
          } = require(`@/api/${this.module}`);
          let {
            info
          } = await destroy(id);
          this.$message.success(info);
          await this.fetchData();
        } catch (error) {
          this.$message({
            type: "info",
            message: "Cancelled deletion"
          });
        }
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>